import React, {lazy ,Suspense} from "react";
import {Redirect, Route, Switch} from "react-router-dom"
import PropTypes from "prop-types"

import uuid from "../utils/uuid";
import routeTable, { beforeEach } from "./routeTable";

function map(routeTable) {
    const fn = (rt, path) => {
        return rt.map(route => {
            route.key = uuid()
            route.path = (/^\//).test(route.path)
                ? route.path
                : ((path === '/' ? '' : path) + '/' + route.path)

            if (beforeEach) {
                const bf = route.beforeEach
                route.beforeEach = route => {
                    let path = beforeEach(route)
                    if (bf) path = bf(route)
                    return path
                }
            }
            if (route.children) {
                route.children = fn(route.children, route.path)
            }
            return route
        })
    }
    return fn(routeTable, '')
}

function RouterView(props) {
    return (
        <Switch>
            {
                props.routes.map(route => {
                    /*console.log(route)*/
                    if (route.redirect) {
                        return <Redirect key={ route.key } from={ route.path } to={ route.redirect } />
                    } else {
                        return (
                            <Route
                                key={ route.key }
                                path={ route.path }
                                render={props => {
                                    if (route.beforeEach) {
                                        let path = route.beforeEach(route)
                                        if (path !== route.path) return <Redirect key={ route.key } from={ route.path } to={ path } />
                                    }

                                    let View = lazy(route.view)
                                    return (
                                        <Suspense fallback={ <></> }>
                                            <View routes={ route.children || [] } {...props} />
                                        </Suspense>
                                    )
                                }}
                            />
                        )
                    }
                })
            }
        </Switch>
    )

}

RouterView.propTypes = {
    routes: PropTypes.array
}

RouterView.defaultProps = {
    routes: []
}

const routes = map(routeTable)

export { routes }

export default RouterView
